<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-6-3
 * Time: 下午1:34
 * @author 郑钟良<zzl@ourstu.com>
 */

namespace Appstore\Model;


use Think\Model;

class AppstoreOrderModel extends Model
{
    protected $_auto = array(
        array('id', 'randId', self::MODEL_INSERT, 'callback'),
        array('create_time', NOW_TIME, self::MODEL_INSERT),
        array('status', '1', self::MODEL_INSERT),
        array('pay_ok', '0', self::MODEL_INSERT),
        array('pay_time', '0', self::MODEL_INSERT),
    );

    public function createOrderList($data, $versions)
    {
        $data['uid'] = get_uid();
        $dataList = array();
        $versionModel = D('Appstore/AppstoreVersion');
        foreach ($versions as $val) {
            $data['version_id'] = $val;
            $version = $versionModel->where(array('id' => $val, 'status' => 1))->find();
            if (!$version) {
                continue;
            }
            $data['goods_id'] = $version['goods_id'];


            $map['version_id'] = $data['version_id'];
            $map['goods_id'] = $data['goods_id'];
            $map['uid'] = $data['uid'];
            $info = $this->where($map)->find();
            if ($info) {
                if (!$this->isPayed($info['version_id'], $info['uid'])) {
                    if ($info['payment_price']) {
                        $this->where($map)->setField('payment_price', 0);
                    }
                    $this->afterPay($info['id']);
                }
            } else {
                $data = $this->create($data);
                $data['id'] = $this->randId();
                $dataList[] = $data;
            }
        }
        if (count($dataList)) {
            $res = $this->addAll($dataList);
            foreach ($dataList as $val) {
                $this->afterPay($val['id']);
            }
        } else {
            return true;
        }
        return $res;
    }

    public function isPayed($version_id, $uid)
    {

        $version = D('AppstoreVersion')->getVersion($version_id);
        $goods = D('AppstoreGoods')->find($version['goods_id']);
        if ($goods['entity'] != 4){
            if (check_auth('Appstore/Admin/manage', array($goods['uid']))) {
                return true;
            }
        }
        $max = D('AppstorePriceMax')->where(array('goods_id' => $version['goods_id'], 'uid' => $uid))->order('last_version_id desc')->find();
        $last_version_id = $max['last_version_id'];

        //todo 已购买。
        if(!empty($max)){
            return true;
        }

        if ($last_version_id >= $version_id) {
            return true;
        }
        return false;
        //return  $this->where(array('version_id' => $version_id, 'uid' => $uid, 'pay_ok' => 1))->count();

    }


    protected function randId()
    {
        $id = time() . create_rand(4, 'num');
        return doubleval($id);
    }


    public function getById($id)
    {
        $order = $this->where(array('status' => array('egt', 0), 'id' => $id))->find();
        return $order;
    }


    public function createOrder($data)
    {
        $data = $this->create($data);
        if (!$data) return false;
        $result = $this->add($data);
        if (!$result) {
            return false;
        }

        D('order_link')->add(array('order_id' => $result, 'model' => 'appstore_order', 'app' => 'appstore'));
        return $result;
    }

    public function cancelOrder($order_id)
    {
        return $this->where(array('id' => $order_id))->setField('status', 0);
    }

    public function payOk($order_id)
    {

        $order = $this->getById($order_id);
        $memberModel = D('Member');

        if ($order['uid'] != get_uid()) {
            $this->error = '该订单不是您的。无法付款。';
            return false;
        }

        if ($order['pay_ok'] != 0) {
            $this->error = '该订单不是未支付状态。';
            return false;
        }

        if ($order['payment_price']) {
            $scoreModel = D('Ucenter/Score');
            $currency = $scoreModel->getUserScore($order['uid'], $order['score']);
            $left = $currency - $order['payment_price'];
            if ($left < 0) {
                $score = D('Ucenter/Score')->getType(array('id' => $order['score']));
                $this->error = $score['title'] . '不足。';
                return false;
            }

            D('Ucenter/Score')->setUserScore($order['uid'], $order['payment_price'], $order['score'], 'dec', 'appstore_order', $order_id, get_nickname($order['uid']) . '支付了云平台的订单');

        }

        return $this->afterPay($order_id);

    }

    public function afterPay($order_id)
    {
        $order = $this->getById($order_id);
        $goods = D('AppstoreGoods')->getById($order['goods_id']);
        $data['pay_ok'] = 1;
        $data['status'] = 1;
        $data['pay_time'] = time();
        $this->where(array('id' => $order_id))->save($data);

        /*注意！！！！！此处的运行环境可能并不是在客户浏览器端，可能是支付宝发起的请求，所以严禁使用get_uid和is_login等函数*/

        $scoreType = D('Ucenter/Score')->getType(array('id' => $order['score']));
        D('Common/Message')->sendMessageWithoutCheckSelf($goods['uid'], '应用商店商品已售出', "您的商品 " . $goods['title'] . " 已经售出，您的" . $scoreType['title'] . "增加了 " . $order['payment_price'] . $scoreType['unit'] . '。', 'Appstore/Index/goodsdetail', array('id' => $goods['id']), $order['uid'], 2);
        D('Ucenter/Score')->setUserScore($goods['uid'], $order['payment_price'], $order['score'], 'inc', 'appstore_order', $order_id, get_nickname($goods['uid']) . '收到了订单的款');
        $price = D('AppstorePrice')->where(array('pid' => 0, 'version_id' => $order['version_id']))->select();
        foreach ($price as $val) {
            $price_max = D('AppstorePriceMax')->where(array('goods_id' => $order['goods_id'], 'score_id' => $val['value'], 'uid' => $order['uid']))->find();
            if ($price_max) {
                $price_max['max_price'] = $price_max['max_price'] > $val['price'] ? $price_max['max_price'] : $val['price'];
                $price_max['last_version_id'] = $order['version_id'];
                D('AppstorePriceMax')->save($price_max);
            } else {
                $price_max['goods_id'] = $order['goods_id'];
                $price_max['score_id'] = $val['value'];
                $price_max['uid'] = $order['uid'];
                $price_max['max_price'] = $val['price'];
                $price_max['last_version_id'] = $order['version_id'];
                D('AppstorePriceMax')->add($price_max);
            }
        }


        D('AppstoreVersion')->where(array('id' => $order['version_id']))->setInc('sales');
        D('AppstoreGoods')->where(array('id' => $order['goods_id']))->setInc('sales');
        D('AppstoreDeveloper')->where(array('uid' => $goods['uid']))->setInc('sales');

        return true;
    }

}